<?php

/*
 * 摇一摇页面主入口文件
 */
namespace Portal\Controller;

use Library\User;
use Library\Wx;
use Portal\Controller\CommonController;
use Library\Prizes\Prizes;
use Library\CardCode;
use Think\Log;

/**
 * 首页
 */
class IndexController extends CommonController {
    /*
     *  限制从从微信进入
     */
    private function checkSource() {
        if ($this->isWeixin() == false) {
            $this->assign('isWX', 1);
            $this->display(':illustrate');
            exit;
        } else {
            $this->weixin_auth();
        }
    }

    /*
     *  限制从微信摇一摇进入
     */
    private function checkShake() {
        $shark_openid = $_SESSION['open_id'];
        if ($shark_openid) {
            $user_shake_ts = S('shake_event_ts:'.$shark_openid);
//          if (APP_ENV === 'ONLINE') { //测试环境不限制从摇一摇进入
//              if ($user_shake_ts == FALSE) {
//                  $this->display(':timeout');
//              }
//          } else {
//              $Beacon = \Library\Beacon::getInstance();
//              $Beacon->moniShake();
//          }
            if ($user_shake_ts == FALSE) {
                $this->statistics_log('checkShake timeout');
                $this->display(':timeout');
                exit;
            } else {
                if ($user_shake_ts['ChosenBeacon']) {
                    $this->addShareInfo($user_shake_ts['ChosenBeacon']);
                } else {
                }
            }
        }
    }

    //签到
    public function qiandao() {
        $this->statistics_log();
        $shake = new \Library\Shake();
        $ever = $shake->evercheck();
		echo $ever;
    }
    //完善个人信息页
    public function xiangxi() {
        $this->checkSource();
        $this->statistics_log();
        $shake = new \Library\Shake();
        $real = $shake->material();
        $this->assign('uinfo', $real);
        $this->assign('ticket',WEB_DOMAIN.S('TICKET/'.$_SESSION['open_id']));
        $this->display(":profile");
    }
    //验证手机号页面
    public function verify_phone() {
        $this->display(":verify_phone");
    }
    //勋章页
    public function xunzhang() {
        $this->checkSource();
        $this->statistics_log();
        $this->display(":xunzhang");
    }
    //首页
    public function index() {
        $this->statistics_log();
        $this->checkSource();
        $shake = new \Library\Shake();
        $event = $shake->get_activity_by_pageId();
		$device = $shake->get_device_loding();
        $this->checkShake();
        if ($event) {
        	S('TICKET/'.$_SESSION['open_id'],$_SERVER['REQUEST_URI'],3600);
			F('EVENT/ID',$event['id']);
			F('EVENT/TYPE',$event['event_type']);
            $pageinfo['bg_pic'] = $event['bg_pic'] != '' ? C('IMG_PATH').$event['bg_pic'] : '';
            $pageinfo['loding_pic'] = $device != '' ? $device : $event['loding_pic'];
            $pageinfo['center_pic'] = $event['center_pic'];
            $pageinfo['event_intro'] = $event['event_intro'];
            $this->assign('pageinfo', $pageinfo);
        } else {
            $this->redirect('yure');
        }
        Log::record('isFirst:'.$shake->isFirst());
        $this->assign('first_visit', $shake->isFirst());

        $user_wallet = new \Library\UserWallet();
        $money = $user_wallet->get_user_money();
        $this->assign('money', $money / 100);
        $this->assign('user_info', $_SESSION['wxuser']);
        $this->addJsSdk();
        $this->display(":index");
    }

    //预览页面
    public function yure() {
        $this->checkSource();
        $this->statistics_log();
        $this->display(":yure");
    }
    //夺宝
    public function duobao() {
        $this->checkSource();
        $this->statistics_log();
        //echo "<script>window.location.href = '".WEB_DOMAIN."/duobao/?/mobile/mobile/';</script>";
        $source = $_GET['source'];
        $query_string = $_GET['query_string'];
        if ($source) {
            redirect(WEB_DOMAIN.$source);
        } else {
            redirect(WEB_DOMAIN.'/duobao/?'.$query_string);
        }
    }
    /*
     * 分享后的,其他用户打开后的主页
     */
    public function shareIndex(){
        do {
            $userMarkEncrypt = $_GET['u'];
            $devMarkEncrypt = $_GET['d'];
            if ($userMarkEncrypt == '' || $devMarkEncrypt == '') {
                break;
            }

            $userMark = aesDecrypt($userMarkEncrypt);
            $devMark = aesDecrypt($devMarkEncrypt);
            if ($devMark == false || $userMark == false) {
                break;
            }

            $data['object_id'] = 3;  //分享页
            $data['userid'] = $_SESSION['user_id'];
            $data['openid'] = $_SESSION['open_id'];

            if ($_SESSION['devid']) {
                $data['devid'] = $devMark;
            }
            D('statistics')->add($data);

            $where['devid'] =$devMark;
            $device =  D('Device')->where($where)->find();
            $store =  D('Store')->where(array('store_id'=>$device['store_id']))->find();
            $storeName = $store['title'];
            $cover = $store['cover'];
            if ($store['longitude'] && $store['latitude']) {
                $coordinate['longitude'] = $store['longitude'];
                $coordinate['latitude'] = $store['latitude'];
            }
            $where['weixin_id'] = ($userMark);
            $userinfo = D('real_users')->field('nickname, weixin_avatar')->where($where)->find();
            if ($userinfo) {
                $this->assign('user_info', $userinfo);
            } else {
                break;
            }
            $where['openid'] = $userMark;
            $prizes = D('prizes_order')->field('card_id, event_id')->where($where)->order('winning_time desc')->find();
            if ($prizes) {
                $where['id'] = $prizes['card_id'];
                $card = D('card')->field('congratulations')->where($where)->find();
                $congratulations = $card['congratulations'];
            } else {
                $congratulations = '';
            }
            $this->assign('congratulations', $congratulations);
            $this->assign('storeName', $storeName);
            $this->assign('coordinate', $coordinate);
            $this->assign('storeCover', $cover ? C('APP_IMG_PATH').$cover : C('IMG_PATH').'static/img/head_pic.jpg');
            $this->display(':share');
            exit;
        } while(0);
        $this->display(':timeout');
    }

    //摇一摇超时页面
    public function shakeTimeout() {
        if ($this->isWeixin() == false) {
            $this->assign('isWX', 1);
            $this->display(':illustrate');
            exit;
        }

        $this->statistics_log();
        $this->display(":timeout");
    }

    //个人账户中心
    public function honghongbao() {
        $this->checkSource();

        $user_wallet = new \Library\UserWallet();
        $money = $user_wallet->get_user_money();

        $cardCode = CardCode::getInstance();
        $userCards = $cardCode->getAllUserCard();

        $shake = new \Library\Shake();
        $real = $shake->ad(1);
        $this->assign('user_info', $_SESSION['wxuser']);
        $this->assign('money', $money / 100);
        $this->assign('userCards', $userCards);
        $this->assign('real', $real);
        $this->display(":honghongbao");

        $this->statistics_log();
    }
    /*
     * 提现页面
     */
    public function getdeposit() {
        $this->checkSource();

        $user_wallet = new \Library\UserWallet();
        $money = $user_wallet->get_user_money();

        $txCount =  $user_wallet->getTxCountByCurMonth();

        $shake = new \Library\Shake();
        $real = $shake->ad(2);

        $this->assign('tixian_count_used_month', $txCount);
        $this->assign('tixian_count_total_month', C('TIXIAN_COUNT_TOTAL_MONTH'));
        $this->assign('user_info', $_SESSION['wxuser']);
        $this->assign('money', $money / 100);
        $this->assign('real', $real);
        $this->display(":getdeposit");

        $this->statistics_log();
    }
    /*
     * 提现成功页面
     */
    public function getdepositsuccess() {
        $this->checkSource();

        $user_wallet = new \Library\UserWallet();
        $money = $user_wallet->get_user_money();
        $txCount =  $user_wallet->getTxCountByCurMonth();

        $this->assign('tixian_count_used_month', $txCount);
        $this->assign('tixian_count_total_month', C('TIXIAN_COUNT_TOTAL_MONTH'));
        $this->assign('user_info', $_SESSION['wxuser']);
        $this->assign('money', $money / 100);
        $this->assign('ticket',WEB_DOMAIN.S('TICKET/'.$_SESSION['open_id']));
        $this->display(":getdepositsuccess");
        $this->statistics_log();
    }
    /*
     * 卡券详情页面
     */
    public function cardDetail() {
        $this->checkSource();

        $code = $_GET['cardCode'];
        $cardId = $_GET['cardId'];

        $cardCode = CardCode::getInstance();
        $cardDetail = $cardCode->getCardDetail($cardId, $code);

        if ($cardDetail) {
            $this->assign('cardDetail', $cardDetail);
            $this->display(':mycard_detail');
        } else {
            $this->assign('info', '无效的卡券');
            $this->display(':tips');
        }
        $this->statistics_log();
    }

    /*
     *  页面点击统计
     */
    public function analytics() {
        $this->urlAnalytics();
        $this->statistics_log();
        $real_url = $_GET['real_url'];
        redirect($real_url);
    }
    public function urlAnalytics() {
        $analysislog = C('LOG_REAL_PATH')."/Analysis/".date('y_m_d').'url.log';

        $tongji['openid'] = $_SESSION['open_id'];
        if ($_GET) {
            $tongji['eid'] = F('EVENT/ID');
            $tongji['etype'] = F('EVENT/TYPE');
            $tongji['cid'] = $_GET['mark']-1000000;
            $tongji['ctype'] = $_GET['ctype'];
        } else {
            $tongji['eid'] = 0;
            $tongji['etype'] = 0;
            $tongji['cid'] = 0;
            $tongji['ctype'] = 0;
        }
        $tongji['time'] = date('Y-m-d H:i:s', time());
		\Think\Log::write(json_encode($tongji), 'JSON', NULL, $analysislog);
    }

    /**
     * @param url 要生成的二维码的链接
     * @param flag 是否生成图片保存起来，1是，0否（只是动态生成）
     */
	public function createQRcode() {
        createQRcode(I('get.num'), 0);
    }
    /*
     * H5 核销卡券页面
     */
    public function  verification() {
        $code = $_GET['card_num'];
        $cardId = $_GET['card_id'];

        $cardCode = CardCode::getInstance();
        $cardDetail = $cardCode->getCardDetail($cardId, $code);

        if ($cardDetail) {
            $this->assign('cardDetail', $cardDetail);
        }

        $this->display(':verification');
    }

    //增加微信分享相关信息
    private function addShareInfo($deviceInfo) {
        $where['uuid'] = $deviceInfo['Uuid'];
        $where['major'] = $deviceInfo['Major'];
        $where['minor'] = $deviceInfo['Minor'];
        $device =  D('Device')->where($where)->find();
        $_SESSION['devid'] = $device['devid'];
        $userMark = aesEncrypt($_SESSION['open_id']);
        $devMark = aesEncrypt($device['devid']);
        $url = U('Portal/Index/shareIndex', array('u'=> $userMark, 'd'=> $devMark));
        $store =  D('Store')->where(array('store_id'=>$deviceInfo['store_id']))->find();
        $this->assign('shareUrl', WEB_DOMAIN.$url);
        $this->assign('storeName', $store['title']);
    }

    // 增加卡券信息
    private function addCard() {
        $url = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
        $js_sign = Wx::getJsSign($url);

        //$arg['cardid'] = 'pMcfvsiGkTeBmKvhjVpkZv-dLCq0';
        $arg['cardid'] = 'p9Vj9vgCSAR6d8HnhrzDV8AAHeI4';
        $arg['cardCode'] = '1233333213';
        $jscard_sign = Wx::getJsCardSign($arg);

        $this->assign('cardid', 'p9Vj9vgCSAR6d8HnhrzDV8AAHeI4');
        $this->assign('js_sign', $js_sign);
        $this->assign('jscard_sign', $jscard_sign);
    }

    private function addJsSdk() {
        $url = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
        $js_sign = Wx::getJsSign($url);

        $this->assign('js_sign', $js_sign);
    }

    private function getOpenid() {
        $openid = $_SESSION['open_id'];

        if (!empty($openid)) {
            $this->assign('openid', $openid);
        } else {
            $this->assign('openid', '');
        }
    }
}